from fastapi import APIRouter, HTTPException, Depends, UploadFile, File, Form, Query
from typing import Optional, List
import logging
import traceback
import json
import os
from pydantic import BaseModel
from fastapi.responses import JSONResponse

# 导入数据库
from database import get_db_cursor
import database

# 导入认证相关模块
from auth import get_current_user, User, get_user_id_from_token

# 设置日志
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# 创建路由器
router = APIRouter(tags=["profile"])

# 定义请求模型
class ProfileUpdate(BaseModel):
    full_name: Optional[str] = None
    bio: Optional[str] = None
    music_identity: Optional[str] = None
    main_instrument: Optional[str] = None
    preferences: Optional[List[str]] = None

# 定义响应模型
class ProfileResponse(BaseModel):
    id: int
    username: str
    email: str
    full_name: Optional[str] = None
    bio: Optional[str] = None
    avatar_url: Optional[str] = None
    music_identity: Optional[str] = None
    main_instrument: Optional[str] = None
    preferences: Optional[List[str]] = None
    stats: dict = {}

# 处理CORS预检请求
@router.options("/{path:path}")
async def options_handler(path: str):
    """处理所有OPTIONS预检请求，返回正确的CORS头信息"""
    response = JSONResponse({})
    response.headers["Access-Control-Allow-Origin"] = "*"
    response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS"
    response.headers["Access-Control-Allow-Headers"] = "*"
    response.headers["Access-Control-Allow-Credentials"] = "true"
    return response

@router.get("/me")
async def get_profile(current_user: User = Depends(get_current_user)):
    """获取当前登录用户的个人资料"""
    try:
        logger.info(f"获取用户个人资料 - 用户ID: {current_user.id}")
        
        # 调用数据库函数获取用户完整资料
        user_profile = database.get_user_profile(current_user.id)
        
        if not user_profile:
            logger.warning(f"找不到用户资料: {current_user.id}")
            raise HTTPException(status_code=404, detail="用户资料不存在")
        
        # 获取用户统计数据
        user_stats = database.get_user_stats(current_user.id)
        user_profile["stats"] = user_stats
        
        return user_profile
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取用户资料失败: {str(e)}")
        logger.error(traceback.format_exc())
        raise HTTPException(status_code=500, detail=f"获取用户资料失败: {str(e)}")

@router.put("/me")
async def update_profile(
    profile: ProfileUpdate,
    current_user: User = Depends(get_current_user)
):
    """更新当前登录用户的个人资料"""
    try:
        logger.info(f"更新用户个人资料 - 用户ID: {current_user.id}")
        
        # 转换为字典并移除None值
        update_data = profile.dict(exclude_unset=True)
        
        # 如果有preferences字段且不为None，转换为JSON字符串
        if "preferences" in update_data and update_data["preferences"] is not None:
            update_data["preferences"] = json.dumps(update_data["preferences"])
        
        # 调用数据库函数更新用户资料
        success = database.update_user_profile(current_user.id, update_data)
        
        if not success:
            logger.warning(f"更新用户资料失败: {current_user.id}")
            raise HTTPException(status_code=500, detail="更新用户资料失败")
        
        # 获取更新后的用户资料
        updated_profile = database.get_user_profile(current_user.id)
        
        # 获取用户统计数据
        user_stats = database.get_user_stats(current_user.id)
        updated_profile["stats"] = user_stats
        
        return updated_profile
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"更新用户资料失败: {str(e)}")
        logger.error(traceback.format_exc())
        raise HTTPException(status_code=500, detail=f"更新用户资料失败: {str(e)}")

@router.post("/avatar")
async def update_avatar(
    avatar: UploadFile = File(...),
    current_user: User = Depends(get_current_user)
):
    """更新用户头像"""
    try:
        logger.info(f"更新用户头像 - 用户ID: {current_user.id}")
        
        # 确保上传目录存在
        temp_dir = os.path.join("static", "temp")
        os.makedirs(temp_dir, exist_ok=True)
        
        # 生成临时文件名
        import uuid
        ext = os.path.splitext(avatar.filename)[1]
        temp_filename = f"temp_avatar_{uuid.uuid4()}{ext}"
        temp_file_path = os.path.join(temp_dir, temp_filename)
        
        # 保存上传文件到临时目录
        with open(temp_file_path, "wb") as f:
            content = await avatar.read()
            f.write(content)
        
        # 使用cos_utils上传到腾讯云
        import cos_utils
        cos_file_path = f"avatars/user_{current_user.id}{ext}"
        avatar_url = cos_utils.upload_file(temp_file_path, cos_file_path)
        
        # 上传成功后删除临时文件
        try:
            os.remove(temp_file_path)
        except Exception as e:
            logger.warning(f"删除临时文件失败: {str(e)}")
        
        # 更新数据库中的头像URL
        success = database.update_user_avatar(current_user.id, avatar_url)
        
        if not success:
            logger.warning(f"更新用户头像失败: {current_user.id}")
            raise HTTPException(status_code=500, detail="更新用户头像失败")
        
        return {"avatar_url": avatar_url}
    except Exception as e:
        logger.error(f"更新用户头像失败: {str(e)}")
        logger.error(traceback.format_exc())
        raise HTTPException(status_code=500, detail=f"更新用户头像失败: {str(e)}")

@router.get("/user/{user_id}")
async def get_user_profile(user_id: int):
    """获取指定用户的公开资料"""
    try:
        logger.info(f"获取用户公开资料 - 用户ID: {user_id}")
        
        # 调用数据库函数获取用户公开资料
        user_profile = database.get_user_public_profile(user_id)
        
        if not user_profile:
            logger.warning(f"找不到用户资料: {user_id}")
            raise HTTPException(status_code=404, detail="用户资料不存在")
        
        # 获取用户统计数据
        user_stats = database.get_user_stats(user_id)
        user_profile["stats"] = user_stats
        
        return user_profile
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取用户公开资料失败: {str(e)}")
        logger.error(traceback.format_exc())
        raise HTTPException(status_code=500, detail=f"获取用户公开资料失败: {str(e)}") 